<template>
	<el-config-provider :locale="zhCn">
		<router-view v-show="getThemeConfig.lockScreenTime !== 0" />
		<Setings ref="setingsRef" v-show="getThemeConfig.lockScreenTime !== 0" />
		<CloseFull />
	</el-config-provider>
</template>

<script lang="ts">
import { computed, onBeforeUnmount, ref, getCurrentInstance, onBeforeMount, onMounted, onUnmounted, nextTick, defineComponent, watch, reactive, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useThemeConfigStateStore } from '@/stores/themeConfig';
import { useTagsViewRoutesStore } from '@/stores/tagsViewRoutes';
import other from '@/utils/other';

import { Local, Session } from '@/utils/storage';
import setIntroduction from '@/utils/setIconfont';
import Setings from '@/layout/navBars/breadcrumb/setings.vue';
import CloseFull from '@/layout/navBars/breadcrumb/closeFull.vue';
import zhCn from 'element-plus/dist/locale/zh-cn.mjs';
import Cookies from 'js-cookie';
import { goAuth } from '@/utils/util';

const BASE_URL = import.meta.env.VITE_API_URL;

export default defineComponent({
	name: 'app',
	components: { Setings, CloseFull },
	setup() {
		const { proxy } = getCurrentInstance() as any;
		const setingsRef = ref();
		const route = useRoute();
		const router = useRouter();
		const theme = useThemeConfigStateStore();
		const tagsViewRoutes = useTagsViewRoutesStore();
		const state: any = reactive({
			i18nLocale: null,
			TIMER: null, // 定时器
		});

		const coverFetch = () => {
			// 保存原生的 fetch 方法（可选，可用于恢复）
			const originalFetch = window.fetch;

			/**
			 * 封装 fetch 方法，覆盖全局 fetch，并添加响应拦截
			 * @param {RequestInfo} input - 请求的 URL 或 Request 对象
			 * @param {RequestInit} [init] - 可选的请求配置
			 * @returns {Promise<Response>} - 返回处理后的响应
			 */
			window.fetch = async function (input, init) {
				try {
					// 调用原生 fetch
					const response = await originalFetch(input, init);

					// 拦截 413 状态码
					if (response.status === 413) {
						goAuth(); // 调用认证函数
						throw new Error("Request too large (413), authentication required");
					}

					return response; // 返回正常响应
				} catch (error) {
					console.error("Fetch error:", error);
					throw error; // 重新抛出错误
				}
			};
		}

		// 获取布局配置信息
		const getThemeConfig = computed(() => {
			return theme.themeConfig;
		});
		// 布局配置弹窗打开
		const openSetingsDrawer = () => {
			setingsRef.value.openDrawer();
		};
		// 订阅消息
		const subscribe = () => {
			const eventSource = new EventSource(`/api/event/heartbeat`);
			// 处理自定义事件
			eventSource.addEventListener('message', async (event) => {
				const customData = JSON.parse(event.data);
				console.log('收到自定义事件:', customData);
			});
			eventSource.addEventListener('info', async (event) => {
				const customData = JSON.parse(event.data);
				console.log('收到自定义事件:', customData);
			});
			eventSource.addEventListener('warning', async (event) => {
				const customData = JSON.parse(event.data);
				console.log('收到自定义事件:', customData);
			});
		}

		// 设置初始化，防止刷新时恢复默认
		onBeforeMount(() => {
			// 设置批量第三方 icon 图标
			setIntroduction.cssCdn();
			// 设置批量第三方 js
			setIntroduction.jsCdn();
		});
		// 页面加载时
		onMounted(() => {
			coverFetch()
			nextTick(() => {
				// 监听布局配置弹窗点击打开
				proxy.mittBus.on('openSetingsDrawer', () => {
					openSetingsDrawer();
				});
				// 获取缓存中的布局配置
				const config = { ...Local.get('themeConfig') };
				config.wartermarkText = Cookies.get('nickname') + ' ' + new Date().toLocaleDateString() || '';
				if (Local.get('themeConfig')) {
					theme.setThemeConfig(config);
					document.documentElement.style.cssText = Local.get('themeConfigStyle');
				}
				// 获取缓存中的全屏配置
				if (Session.get('isTagsViewCurrenFull')) {
					tagsViewRoutes.setCurrenFullscreen(Session.get('isTagsViewCurrenFull'));
				}
				setTimeout(() => {
					console.log('页面加载时', route.path);
					if (route.path != '/login' && state.TIMER == null) {
						state.TIMER = setInterval(() => {
							subscribe();
						}, 10 * 60 * 1000)
					}
				}, 1000)
			});

		});

		// 页面销毁时，关闭监听布局配置/i18n监听
		onUnmounted(() => {
			proxy.mittBus.off('openSetingsDrawer', () => { });
			proxy.mittBus.off('getI18nConfig', () => { });
			clearInterval(state.TIMER);
		});
		// 监听路由的变化，设置网站标题
		watch(
			() => route.path,
			() => {
				if (route.path == '/page') return;
				other.useTitle();
				// 过期接口请求会413，跳转登录页，这里暂时不需要前端判断
				// const expire = localStorage.getItem('expire');
				// if (Date.now() > Number(expire) * 1000 && route.path != '/login') {
				// 	// 过期
				// 	Session.clear(); // 清除缓存/token等
				// 	router.push('');
				// }
			}
		);
		return {
			zhCn,
			setingsRef,
			getThemeConfig,
			...toRefs(state),
		};
	},
	mounted() {
		console.info = function () { };
		console.warn = function () { };
		console.error = function () { };
	},
});
</script>

<style>
input:-internal-autofill-previewed,
input:-internal-autofill-selected {
	transition: background-color 5000s ease-in-out 0s !important;
}
</style>
